package com.alex.taskmanager.serializer.json;

import com.alex.taskmanager.serializer.Serializer;
import com.alex.taskmanager.serializer.SerializerException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class JsonSerializer implements Serializer {
	
	private static final String DELIM = "\n\n";

	private GsonBuilder gsonBuilder = new GsonBuilder();
	
	private Gson gson = gsonBuilder.create();

	public String serialize(Object object) {
		return object.getClass().getName() + DELIM + gson.toJson(object);
	}

	public Object deserialize(String data) throws SerializerException {
		int p = data.indexOf(DELIM);
		try {
			return gson.fromJson(data.substring(p + DELIM.length()), Class.forName(data.substring(0, p)));
		} catch (JsonSyntaxException e) {
			throw new SerializerException(e);
		} catch (ClassNotFoundException e) {
			throw new SerializerException(e);
		}
	}

}
